package me.shurufa.fragments;

import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.LinearLayout;

import com.google.gson.Gson;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import butterknife.Bind;
import butterknife.ButterKnife;
import in.srain.cube.views.ptr.PtrDefaultHandler;
import in.srain.cube.views.ptr.PtrFrameLayout;
import in.srain.cube.views.ptr.PtrHandler;
import me.shurufa.R;
import me.shurufa.adapter.BookCatalogAdapter;
import me.shurufa.model.CatalogListResponse;
import me.shurufa.net.API;
import me.shurufa.net.BaseResponse;
import me.shurufa.net.RequestServerTask;
import me.shurufa.utils.Constants;
import me.shurufa.utils.Global;
import me.shurufa.utils.HttpUtil;
import me.shurufa.utils.LogUtils;
import me.shurufa.utils.NetworkUtils;
import me.shurufa.utils.RecyclerViewStateUtils;
import me.shurufa.utils.Utils;
import me.shurufa.widget.LoadingFooter;
import me.shurufa.widget.pulltorefresh.SrfPtrFrameLayout;
import me.shurufa.widget.recyclerview.EndlessRecyclerOnScrollListener;
import me.shurufa.widget.recyclerview.HeaderAndFooterRecyclerViewAdapter;
import me.shurufa.widget.recyclerview.RecyclerViewUtils;

/**
 * 作者 : andy
 * 日期 : 16/3/9 10:31
 * 邮箱 : andyxialm@gmail.com
 * 描述 : 目录Fragment
 */
public class BookCatalogFragment extends BaseLazyListFragment implements View.OnClickListener {
    @Bind(R.id.recycler_view)
    RecyclerView recyclerView;

    @Bind(R.id.ptr_refresh)
    SrfPtrFrameLayout ptrRefresh;

    @Bind(R.id.ll_no_chapter)
    LinearLayout ll_no_chapter;

    @Bind(R.id.btn_tell_need_chapter)
    Button btn_tell_need_chapter;

    @Bind(R.id.fl_content)
    FrameLayout content;

    private BookCatalogAdapter catalogAdapter;
    private ArrayList dataList;
    private HeaderAndFooterRecyclerViewAdapter mHeaderAndFooterRecyclerViewAdapter = null;

    private long bookId;
    private View headerView;

    public static BookCatalogFragment newInstance(long bookId) {
        BookCatalogFragment fragment = new BookCatalogFragment();
        Bundle args = new Bundle();
        args.putLong(Constants.ARG_BOOK_ID, bookId);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            bookId = getArguments().getLong(Constants.ARG_BOOK_ID);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_catalog_list, container, false);
        ButterKnife.bind(this, view);
        return view;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.unbind(this);
    }

    @Override
    protected void initUI(View view) {
        super.initUI(view);
//        初始化刷新
        setRefresh();
        dataList = new ArrayList();
        catalogAdapter = new BookCatalogAdapter(this, dataList);
        mHeaderAndFooterRecyclerViewAdapter = new HeaderAndFooterRecyclerViewAdapter(catalogAdapter);
        recyclerView.setAdapter(mHeaderAndFooterRecyclerViewAdapter);
        recyclerView.setOverScrollMode(View.OVER_SCROLL_NEVER);
        recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));

        initHeader();
        RecyclerViewUtils.setHeaderView(recyclerView, headerView);
        recyclerView.addOnScrollListener(mOnScrollListener);
        btn_tell_need_chapter.setOnClickListener(this);
    }

    private void initHeader() {
        headerView = LayoutInflater.from(getActivity()).inflate(R.layout.item_header_gray, recyclerView,false);
    }

    private EndlessRecyclerOnScrollListener mOnScrollListener = new EndlessRecyclerOnScrollListener() {

        @Override
        public void onLoadNextPage(View view) {
            super.onLoadNextPage(view);
            try {
                LoadingFooter.State state = RecyclerViewStateUtils.getFooterViewState(recyclerView);
                if (state == LoadingFooter.State.Loading) {
                    LogUtils.kLog().e("the state is Loading, just wait..");
                    return;
                }

                if (hasMore) {
                    // loading more
                    RecyclerViewStateUtils.setFooterViewState(getActivity(), recyclerView, Constants.PAGE_REQUEST_COUNT, LoadingFooter.State.Loading, null);
                    loadData(mPage);
                } else {
                    //the end
                    RecyclerViewStateUtils.setFooterViewState(getActivity(), recyclerView, Constants.PAGE_REQUEST_COUNT, LoadingFooter.State.TheEnd, null);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    };

    private void setRefresh() {
        ptrRefresh.setResistance(2.0F);
        ptrRefresh.setRatioOfHeaderHeightToRefresh(1.0F);
        ptrRefresh.setDurationToClose(300);
        ptrRefresh.setDurationToCloseHeader(1000);
        ptrRefresh.setLoadingMinTime(500);
        ptrRefresh.setPullToRefresh(false);
        ptrRefresh.setKeepHeaderWhenRefresh(true);
        ptrRefresh.disableWhenHorizontalMove(true);
        ptrRefresh.setPtrHandler(new PtrHandler() {
            @Override
            public boolean checkCanDoRefresh(PtrFrameLayout ptrFrameLayout, View view, View view1) {
                boolean canbePullDown = PtrDefaultHandler.checkContentCanBePulledDown(ptrFrameLayout, view, view1);
                return canbePullDown;
            }
            @Override
            public void onRefreshBegin(PtrFrameLayout ptrFrameLayout) {
                refresh();
            }
        });
    }

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
//        自动刷新一次
//        ptrRefresh.postDelayed(new Runnable() {
//            @Override
//            public void run() {
//                ptrRefresh.autoRefresh(true);
//            }
//        }, 400);
        // refresh();
    }

    @Override
    protected void lazyLoad() {
        refresh();
    }

    @Override
    protected void addDataToList(BaseResponse response, boolean isNew) {
        CatalogListResponse resp = (CatalogListResponse) response;
        if (isNew) {
            catalogAdapter.clear();
        }
        catalogAdapter.append(resp.data);
        catalogAdapter.notifyDataSetChanged();
    }

    @Override
    protected void showEmptyView() {

    }

    @Override
    protected void hideEmptyView() {

    }

    @Override
    protected void setHasMore(boolean hasMore) {

    }

    @Override
    protected BaseResponse parseData(String data) {
        Gson gson = Global.getGson();
        return gson.fromJson(data, CatalogListResponse.class);
    }

    @Override
    public void refresh() {
        super.refresh();
        ptrRefresh.postDelayed(new Runnable() {
            @Override
            public void run() {
                if (ptrRefresh!=null&&ptrRefresh.isRefreshing()) {
                    ptrRefresh.refreshComplete();
                }
            }
        },2000);
        onRefresh();
    }

    public void onRefresh() {
        mPage=1;
        loadData(1);
    }

    private int mPage;
    private boolean hasMore = true;
    private View.OnClickListener mFooterClick = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            RecyclerViewStateUtils.setFooterViewState(getActivity(), recyclerView, Constants.PAGE_REQUEST_COUNT, LoadingFooter.State.Loading, null);
            loadData(mPage);
        }
    };


    protected void loadData(final int page) {
        if (!NetworkUtils.isNetAvailable(getActivity())){
            RecyclerViewStateUtils.setFooterViewState(getActivity(), recyclerView, Constants.PAGE_REQUEST_COUNT, LoadingFooter.State.NetWorkError, this.mFooterClick);
        }else {
            RecyclerViewStateUtils.setFooterViewState(recyclerView, LoadingFooter.State.Loading);
            new RequestServerTask<CatalogListResponse>(CatalogListResponse.class) {
                @Override
                protected String requestServer() {
                    Map<String, Object> params = new HashMap<String, Object>();
                    params.put("bookId", bookId);
                    params.put("page",page);
                    LogUtils.kLog().e("page="+page);
                    return HttpUtil.post(API.GET_BOOK_MENU, params);
                }

                @Override
                protected void onPostExecute(String s) {
                    super.onPostExecute(s);
                    try {
                        endRefreshing();
                        // loadingView.setVisibility(View.GONE);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }

                @Override
                protected void onPreExecute() {
                    super.onPreExecute();
                    try {
                        // loadingView.setVisibility(View.VISIBLE);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }

                // ////////////////Notice！！ 目前目录是一次性全部加载 所以不算分页 加载成功后直接设置已全部加载
                @Override
                protected void onSuccess(CatalogListResponse result) {
                    //没有更多数据 不能加载更多
                    if (result.data == null || result.data.length == 0) {
                        hasMore = false;
                        RecyclerViewStateUtils.setFooterViewState(recyclerView, LoadingFooter.State.TheEnd);

                        if (Utils.isNullForList(dataList)) {
                            content.setVisibility(View.GONE);
                            ll_no_chapter.setVisibility(View.VISIBLE);
                        }
                    } else {
//                        RecyclerViewStateUtils.setFooterViewState(recyclerView, LoadingFooter.State.Normal);
                        RecyclerViewStateUtils.setFooterViewState(recyclerView, LoadingFooter.State.TheEnd);
//                        hasMore = true;
                        hasMore = false;
                        mPage++;
                        bindData(result, page == 1);
                    }
                }
            }.start();
        }
    }

    public void endRefreshing() {
        if (ptrRefresh != null) {
            ptrRefresh.postDelayed(new Runnable() {
                @Override
                public void run() {
                    if (ptrRefresh != null) {
                        ptrRefresh.refreshComplete();
                    }
                }
            }, 500);
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_tell_need_chapter:
                Utils.showToast("还没告诉呢");
                break;
        }
    }

    public RecyclerView findRecyclerView() {
        return recyclerView;
    }
}
